package com.hp.auth_service.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.common_api.util.CookieUtil;
import com.hp.common_api.util.JwtUtil;
import com.hp.common_api.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功的处理
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        try {
            //将用户名转换为JWT
            String token = JwtUtil.generateToken(user.getUsername(), "", "",
                    RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
            //保存到Cookie中
            CookieUtil.setCookie(req,resp,CookieUtil.COOKIE_NAME,token,CookieUtil.COOKIE_MAX_AGE);
            log.info("生成token保存-->" + token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(new ObjectMapper().writeValueAsString(user));
        out.flush();
        out.close();
    }
}
